package com.chaosj.memory.command;

import cn.hutool.core.text.StrFormatter;
import com.chaosj.memory.IToolHandler;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

import java.nio.file.Paths;
import java.util.Arrays;
import java.util.ServiceLoader;

/**
 * @className: HelpCommand
 * @description:
 * @author: caoyangjie
 * @date: 2022/3/22
 **/
@ShellComponent
public class HelpCommand extends AbstractCommand{

    @ShellMethod("man help")
    public String man(String cmd){
        StringBuffer buffer = new StringBuffer("");
        ServiceLoader.load(IToolHandler.class).forEach(handler->{
            if( handler.name().equalsIgnoreCase(cmd) ){
                buffer.append(handler.description());
            }
        });
        return !StringUtils.isEmpty(buffer) ? buffer.toString(): defaultManString();
    }

    @SneakyThrows
    protected String defaultManString(){
        StringBuffer buffer = new StringBuffer();
        Arrays.stream(Paths.get(ClassLoader.getSystemClassLoader().getResource("cmd").toURI()).toFile().listFiles()).forEach(file->{
            buffer.append(StrFormatter.format("man {}\n", file.getName().replace(".command","")));
        });
        return buffer.toString();
    }
}
